import { Injectable } from '@nestjs/common';
import { CachingService } from './caching/caching.service';
import { HttpService } from '@nestjs/axios';
import { DbService } from './db/db.service';
import { Cron, Timeout } from '@nestjs/schedule';
import { ConfigureService } from '@app/configure';

@Injectable()
export class ScheduleService {
    constructor(
      private readonly cache:CachingService,
      private readonly http:HttpService,
      private readonly db:DbService,
      private readonly config:ConfigureService
    ){}


    //系统启动时候，先获取
    @Timeout(0)
    initWXAccessToken(){
        this.getWXAccessToken()
    }

    @Cron('0 * * * *')
    async getWXAccessToken() {
        const platform = await this.db.platformConfig.queryConfig(['wechat'])
        if(!platform || !platform.wechat) return
        const wechat = platform.wechat as any
        if(!wechat.appid || !wechat.secret) return

        const res = await this.http.axiosRef.get('https://api.weixin.qq.com/cgi-bin/token', {
            params : {
                grant_type : 'client_credential',
                appid : wechat.appid,
                secret : wechat.secret
            }
        })

        console.log(res.data.access_token)


        if(res.statusText == 'OK') {
            if(res.data && res.data.access_token) {
                this.cache.set(this.config.get('wxAccessTokenKey'), res.data.access_token)
            }else {
                console.log(res.data)
            }
        }
    }
}
